package java6703.lesson04;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Foreach6703 {
    public static void main(String[] args) {
        //创建：实例化
        ArrayList<Student6703> list = new ArrayList<Student6703>();

        //存储：添加
        list.add(new Student6703("刘一", 18));
        list.add(new Student6703("陈二", 16));
        list.add(new Student6703("张三", 17));
        list.add(new Student6703("李四", 20));
        list.add(new Student6703("王五", 22));

        //用集合的迭代器遍历输出
        useIterator6703(list);

        //用增强for遍历输出
        useForeach6703(list);

        //按序号遍历输出
        useList6703(list);

        //通过数组遍历输出
        useArray6703(list);
    }

    public static void useIterator6703(Collection<Student6703> student6703s) {

        /**
         * 1.对于存储StudentXXXX对象的泛型的集合Collection<E>;
         * 2.用集合的迭代器遍历输出;
         */

        System.out.println("======用集合的迭代器遍历输出======");

        Iterator<Student6703> iterator = student6703s.iterator();


        while (iterator.hasNext()) {
            //循环判断下一个是否为空
            Student6703 student6703 = iterator.next();
            System.out.println(student6703);
        }
    }

    public static void useForeach6703(Collection<Student6703> student6703s) {

        /**
         * 1.对于存储StudentXXXX对象的泛型的集合Collection<E>；
         * 2.用增强for遍历输出;
         */

        System.out.println("======用增强for遍历输出======");

        for (Student6703 student6703 : student6703s) {
            //遍历输出
            System.out.println(student6703);
        }
    }

    public static void useList6703(Collection<Student6703> student6703s) {

        /**
         * 1.对于存储StudentXXXX对象的泛型的集合List<E>；
         * 2.按序号遍历输出;
         */

        System.out.println("======按序号遍历输出======");

        //将集合变为数组给arrayList
        ArrayList arrayList = (ArrayList) student6703s;

        for (int i = 0; i < arrayList.size(); i++) {
            Object obj = arrayList.get(i);
            if (obj instanceof Student6703) {
                System.out.println(obj);
            }
        }
    }


    public static void useArray6703(Collection<Student6703> student6703s) {

        /**
         * 1.对于存储Student6703对象的泛型集合Collection<E>;
         * 2.调用Collection的<T>T[]toArray(T[]a)将集合转为数组;
         * 3.通过数组遍历输出;
         * @param student6703s
         */

        System.out.println("======通过数组遍历输出======");

        Object[] objects = student6703s.toArray();

        for (int i = 0; i < objects.length; i++) {
            if (objects[i] instanceof Student6703) {
                System.out.println(objects[i]);
            }
        }
    }
}